package com.wasp.collector.service;

import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ByteArrayEntity;

import com.wasp.collector.data.RequestContext;
import com.wasp.collector.data.RequestWrapper;
import com.wasp.collector.utils.HttpConstant;

public class DoRequest {
	RequestContext rContext;
	RequestWrapper requestWrapper;

	public DoRequest(RequestContext rContext, RequestWrapper requestWrapper) {
		this.rContext = rContext;
		this.requestWrapper = requestWrapper;
	}

	public HttpUriRequest create() {
		RequestBuilder builder = RequestBuilder.post(rContext.getUrl());
		if (HttpConstant.Method.GET.equalsIgnoreCase(requestWrapper.getMethod())) {
			builder = RequestBuilder.get(rContext.getUrl());
		}
		builder.setConfig(requestWrapper.getRequestConfig()).setCharset(Charset.forName(requestWrapper.getCharset()));
		buildEntity(builder);
		
		HttpUriRequest request = builder.build();
		if (requestWrapper.getHeader() != null && !requestWrapper.getHeader().isEmpty()) {
			for (Map.Entry<String, String> header : requestWrapper.getHeader().entrySet()) {
				request.addHeader(header.getKey(), header.getValue());
			}
		}
		return request;
	}
	private void buildEntity(RequestBuilder builder){
		if(requestWrapper.getBody() != null){
			ByteArrayEntity entity = new ByteArrayEntity(requestWrapper.getBody());
	         entity.setContentType(requestWrapper.getContentType());
	         builder.setEntity(entity);
		}
		 
	}

}